package org.jprobe.utils;

import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.io.File;
import java.net.URI;
import java.net.URL;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

import org.jprobe.JProbeRuntimeException;

/**
 *
 * User interface design utilities, a factory class that contain
 * static methods used in swing objects
 *
 * @author Hussain Al-Mutawa
 * @version 1.0
 */
public final class UIUtils {
	/** dispatch win key for escape method **/
	private transient static final String DISPATCH_WIN_KEY = "com.spodding.tackline.dispatch:WINDOW_CLOSING";
	/** file chooser used to browse for files/directories **/
	public transient static final JFileChooser FILE_CHOOSER = new JFileChooser();

	/** this is a factory class and shall not be initialized since all methods are statics **/
	private UIUtils(){super();}
	/**
	 * Returns an ImageIcon, or null if the path was invalid.
	 * @param path - the path to the image resource in the build directory (jar)
	 * @param description - the text description attached to the image icon
	 * @return image icon
	 */
	public static ImageIcon createImageIcon(final String path,final String description) {
	    final URL url = UIUtils.class.getResource(path);
	    if (url == null) {
	    	throw new JProbeRuntimeException("Couldn't find resource [ " + path + " ]");
	    }
	    return new ImageIcon(url, description);
	}
	/**
	 * opens a URI in web browser using the default operating system
	 *
	 * @param uriLocation the unified resource identifier location to be opened
	 * @throws RuntimeException if the uriLocation is malformed or null
	 */
	public static void openURI(final String uriLocation){
		if(uriLocation==null){
			throw new JProbeRuntimeException("uriLocation is null");
		}
		try {
			final Desktop desktop = java.awt.Desktop.getDesktop();
			final URI uri = new URI(uriLocation);
			desktop.browse(uri);
		} catch (final Exception ex) {
			throw new JProbeRuntimeException(ex);
		}
	}

	/**
	 * gets the coordinates which makes a window perfectly in the screen center
	 * @param window the window from which the dimension is taken to calculate the perfect center
	 * @return the point containing (x,y) coordinates
	 * @throws RuntimeException if the Window is null
	 */
	public static Point getScreenCenterPosition(final Window window){
		if(window==null){
			throw new JProbeRuntimeException("window is null");
		}
		// Get the size of the screen
		final Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

		// Determine the new location of the window
		final int width = window.getSize().width;
		final int height = window.getSize().height;
		final int xCoord = (dim.width-width)/2;
		final int yCoord = (dim.height-height)/2;

		// Move the window
		return new Point(xCoord, yCoord);
	}

	/**
	 * makes a modal dialog closed after hitting the escape (ESC) key
	 * @param dialog
	 * @throws RuntimeException if the dialog is null
	 */
	@SuppressWarnings("serial")
	public static void installEscapeCloseOperation(final JDialog dialog) {
		if(dialog==null){
			throw new JProbeRuntimeException("dialog is null");
		}
		final KeyStroke ESC_STORKE = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);


	    final Action dispatchClosing = new AbstractAction() {
	        public void actionPerformed(final ActionEvent event) {
	            dialog.dispatchEvent(new WindowEvent(
	                dialog, WindowEvent.WINDOW_CLOSING
	            ));
	        }
	    };
	    final JRootPane root = dialog.getRootPane();
	    root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ESC_STORKE, DISPATCH_WIN_KEY);
	    root.getActionMap().put( DISPATCH_WIN_KEY, dispatchClosing);
	}

	/**
	 * browse for a directory to select
	 *
	 * @return the name of the directory selected, empty string otherwise
	 */
	public static String getDirectoy(final String title) {
		FILE_CHOOSER.setName("FILE_CHOOSER");
		FILE_CHOOSER.setCurrentDirectory(new File("./.."));
		FILE_CHOOSER.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
		final int result = FILE_CHOOSER.showDialog(null, title);
		String returnValue;
		if(result==JFileChooser.APPROVE_OPTION){
			returnValue = FILE_CHOOSER.getSelectedFile().getAbsolutePath();
		}else{
			returnValue = "";
		}
		return returnValue;
	}

}
